package cc.rengu.oltp.service.common.dao.impl;

import cc.rengu.jradp.mods.xml.XmlTree;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.dao.SequenceMapper;
import cc.rengu.oltp.service.common.entity.SequenceInfo;
import cc.rengu.oltp.utility.util.DbsUtil;
import cc.rengu.oltp.utility.util.StringUtil;
import cc.rengu.oltp.utility.util.XmlConfigUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;
import cc.rengu.utility.cache.UnifiedCache;
import cc.rengu.utility.dbs.DataBasePool;
import cc.rengu.utility.dbs.DataBasePoolConfig;
import cc.rengu.utility.log.RgLog;
import cc.rengu.utility.log.RgLogger;

/**
 * 数据库Sequence操作实现类
 * Created by 王成 on 2017/11/23.
 */
public class SequenceMapperImpl implements SequenceMapper {
    private final RgLogger rglog = RgLog.getLogger(this.getClass().getName());
    private String dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(AppParamConstant.DATABASE_CONF_NODE, AppParamConstant.OLTP_POOL_NAME);

    public SequenceMapperImpl() throws Exception {
        if (XmlTree.hasThreadTree()) {
            XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
            String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
            if (null != corporation && !corporation.isEmpty()) {
                String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
                dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppParamConstant.OLTP_POOL_NAME);
            }
        }
    }

    @Override
    public String getNextTransSequenceNo(int length) throws Exception {
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        String sqlStr = (String) UnifiedCache.get(AppParamConstant.SQL_MAPPER_CACHE, "getNextTransSequenceNo");
        sqlStr = convSqlStringByDatabaseType(sqlStr);
        SequenceInfo sequenceInfo = new SequenceInfo();
        String transSeqNo;
        int iReturnCode = dbsUtil.dbsExecuteSql(sqlStr, null, sequenceInfo);
        if (0 != iReturnCode) {
            rglog.error("获取交易流水SEQUENCE序号失败,iReturnCode:<{}>", iReturnCode);
            return null;
        }
        transSeqNo = sequenceInfo.getSequenceNo();
        /* 不足长度前补0 */
        if (transSeqNo.length() < length) {
            String format = "%0" + (length - transSeqNo.length()) + "d";
            return String.format(format, 0) + transSeqNo;
        } else {
            return transSeqNo;
        }
    }

    @Override
    public String getNextSmsVerifySeqNo(int length) throws Exception {
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        String sqlStr = (String) UnifiedCache.get(AppParamConstant.SQL_MAPPER_CACHE, "getNextSmsVerifySeqNo");
        sqlStr = convSqlStringByDatabaseType(sqlStr);
        SequenceInfo sequenceInfo = new SequenceInfo();
        String smsVerifySeqNo;
        int iReturnCode = dbsUtil.dbsExecuteSql(sqlStr, null, sequenceInfo);
        if (0 != iReturnCode) {
            rglog.error("获取短信验证码验证SEQUENCE序号失败,iReturnCode:<{}>", iReturnCode);
            return null;
        }
        smsVerifySeqNo = sequenceInfo.getSequenceNo();
        /* 不足长度前补0 */
        if (smsVerifySeqNo.length() < length) {
            String format = "%0" + (length - smsVerifySeqNo.length()) + "d";
            return String.format(format, 0) + smsVerifySeqNo;
        } else {
            return smsVerifySeqNo;
        }
    }

    @Override
    public String getNextSeqNoBySeqName(String seqName, int length) throws Exception {
        if (StringUtil.isEmptyOrNull(seqName)) {
            rglog.error("指定序列名为空:{}", seqName);
            return null;
        }
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        String sqlStr = "select " + seqName.trim() + ".nextval into #sequenceNo from dual";
        sqlStr = convSqlStringByDatabaseType(sqlStr);
        SequenceInfo sequenceInfo = new SequenceInfo();
        String sequenceNumber;
        int iReturnCode = dbsUtil.dbsExecuteSql(sqlStr, null, sequenceInfo);
        if (0 != iReturnCode) {
            rglog.error("获取指定序列<{}>的sequence序号失败,iReturnCode:<{}>", seqName, iReturnCode);
            return null;
        }
        sequenceNumber = sequenceInfo.getSequenceNo();
        /* 不足长度前补0 */
        if (sequenceNumber.length() < length) {
            String format = "%0" + (length - sequenceNumber.length()) + "d";
            return String.format(format, 0) + sequenceNumber;
        } else {
            return sequenceNumber;
        }
    }

    /**
     * 根据数据库类型转换获取Sequence的sql语句
     *
     * @param sqlStr 原始sql
     * @return 转换后的sql
     */
    private String convSqlStringByDatabaseType(String sqlStr) {
        if (DataBasePoolConfig.DB_TYPE_DB2 == DataBasePool.getSessionType(this.dbPoolName)) {
            return sqlStr.replace("from dual", "from Sysibm.sysdummy1");
        } else {
            return sqlStr;
        }
    }
}
